package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;


import com.ruoyi.publish.domain.SysArticleManage;
import com.ruoyi.publish.service.PublishArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/publish/article")
public class SysAticleController extends BaseController {
    @Autowired
    private PublishArticleService publishArticleService;

    /**
     * 获取文章列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysArticleManage sysArticleManage) {
        startPage();
        List<SysArticleManage> list = publishArticleService.selectAticleList(sysArticleManage);
        return getDataTable(list);
    }

    /**
     * 获取文章详情
     */
    @GetMapping(value = "/{articleId}")
    public AjaxResult getInfo(@PathVariable Long articleId) {
        return AjaxResult.success(publishArticleService.selectAticleById(articleId));
    }

    /**
     * 新增文章
     */
    @Log(title = "文章管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@ModelAttribute SysArticleManage sysArticleManage,
                          @RequestParam(value = "image", required = false) MultipartFile file,@RequestParam("parentId")Long parentId) throws IOException {
        if (file != null && !file.isEmpty()) {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
            System.out.println("图片的路径"+avatar);
            sysArticleManage.setImage(avatar);
        }
        //校验文章名是否唯一
        if (!publishArticleService.checkAticleNameUnique(sysArticleManage)) {
            return error("新增文章'" + sysArticleManage.getArticleName() + "'失败，文章名称已存在");
        }
        //校验栏目是否存在
        Long columnId = sysArticleManage.getColumnId();
        if (columnId == null || !publishArticleService.checkColumnExists(columnId)) {
            return error("新增文章'" + sysArticleManage.getArticleName() + "'失败，栏目不存在");
        }

        // 执行修改人
        sysArticleManage.setCreateBy(SecurityUtils.getUsername());
        return toAjax(publishArticleService.insertAticle(sysArticleManage));
    }


    /**
     * 修改文章
     */
    @Log(title = "文章管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@ModelAttribute SysArticleManage sysArticleManage) {
        System.out.println("对象"+sysArticleManage);
        //校验文章名是否唯一
        if (!publishArticleService.checkAticleNameUnique(sysArticleManage))
        {
            return error("修改文章'" + (sysArticleManage.getTitle() != null ? sysArticleManage.getTitle() : "未知") + "'失败，文章名称已存在");
        }
//        校验栏目是否存在
        Long columnId = sysArticleManage.getColumnId();
        if (columnId==null || !publishArticleService.checkColumnExists(columnId))
        {
            return error("修改文章'" + (sysArticleManage.getTitle() != null ? sysArticleManage.getTitle() : "未知") + "'失败，栏目不存在");
        }
        //设置修改人 执行修改
        sysArticleManage.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(publishArticleService.updateAticle(sysArticleManage));

    }
    /**
     * 删除文章
     */
    @Log(title = "文章管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{articleId}")
    public AjaxResult remove(@PathVariable Long articleId) {
        //校验文章是否存在
        if (!publishArticleService.checkAticleExists(articleId)) {
            return error("删除文章失败，文章不存在");
        }
        //执行删除
        return toAjax(publishArticleService.deleteAticleById(articleId));
    }
    /**
     * 批量删除文章
     */
    @Log(title = "文章管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch/{articleIds}")
    public AjaxResult removeBatch(@PathVariable Long[] articleIds) {
        //校验文章是否存在
        for (Long articleId : articleIds) {
            if (!publishArticleService.checkAticleExists(articleId)) {
                return error("删除文章失败，文章ID为" + articleId + "的文章不存在");
            }
        }
        //执行批量删除
        return toAjax(publishArticleService.deleteAticleByIds(articleIds));
    }
    /**
     * 更新文章状态（发布/撤回）
     */
    @Log(title = "文章管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@ModelAttribute SysArticleManage sysArticleManage) {
        // 仅校验必要字段
        Long articleId = sysArticleManage.getArticleId();
        Long columnId = sysArticleManage.getColumnId();
        String status = sysArticleManage.getStatus();

        if (articleId == null) {
            return error("文章ID不能为空");
        }
        if (columnId == null || !publishArticleService.checkColumnExists(columnId)) {
            return error("栏目不存在");
        }
        if (status == null) {
            return error("状态不能为空");
        }
        sysArticleManage.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(publishArticleService.updateStatus(sysArticleManage));
    }

    @PutMapping("/updateStatu")
    public AjaxResult updateStatus(@RequestParam Long articleId,
                                   @RequestParam String status,
                                   @RequestParam(required = false) Integer synced){
        SysArticleManage article=publishArticleService.getArticleId(articleId);
        if(article ==null){
            return AjaxResult.error("文章不存在");
        }
        article.setStatus(status);
        article.setUpdateBy(SecurityUtils.getUsername()); // 设置更新人
        // 执行更新（调用正确的更新方法）
        int rows = publishArticleService.updateStatus(article);
        return rows > 0 ? AjaxResult.success("撤回成功") : AjaxResult.error("撤回失败");

    }

}
